<template>
  <div class="min-h-screen bg-gray-50">
    <div class="container mx-auto px-4 py-8">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-900">我的课程</h1>
        <p class="text-gray-600">学习进度和课程管理</p>
        <div class="mt-4">
          <button
            @click="showCreateCourseModal = true"
            class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
          >
            分享你找到的课程
          </button>
        </div>
      </div>

      <!-- 课程统计 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="bg-white rounded-lg shadow-md p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">总课程数</p>
              <p class="text-2xl font-semibold text-gray-900">{{ stats.totalCourses }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-lg shadow-md p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">已完成</p>
              <p class="text-2xl font-semibold text-gray-900">{{ stats.completedCourses }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-lg shadow-md p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-yellow-100 rounded-full flex items-center justify-center">
                <svg class="w-5 h-5 text-yellow-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">进行中</p>
              <p class="text-2xl font-semibold text-gray-900">{{ stats.inProgressCourses }}</p>
            </div>
          </div>
        </div>

        <div class="bg-white rounded-lg shadow-md p-6">
          <div class="flex items-center">
            <div class="flex-shrink-0">
              <div class="w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center">
                <svg class="w-5 h-5 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"></path>
                </svg>
              </div>
            </div>
            <div class="ml-4">
              <p class="text-sm font-medium text-gray-500">学习时长</p>
              <p class="text-2xl font-semibold text-gray-900">{{ stats.totalHours }}h</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 筛选器 -->
      <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <select
              v-model="selectedStatus"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              @change="handleFilter"
            >
              <option value="">所有状态</option>
              <option value="not-started">未开始</option>
              <option value="in-progress">进行中</option>
              <option value="completed">已完成</option>
            </select>
          </div>
          
          <div>
            <select
              v-model="selectedCategory"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              @change="handleFilter"
            >
              <option value="">所有分类</option>
              <option value="algorithm">算法</option>
              <option value="data-structure">数据结构</option>
              <option value="programming">编程语言</option>
              <option value="system">系统设计</option>
            </select>
          </div>
          
          <div>
            <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索课程..."
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              @input="handleSearch"
            />
          </div>
        </div>
      </div>

      <!-- 提示状态 -->
      <div v-if="loading" class="bg-white rounded-lg shadow-md p-6 mb-6 text-gray-600">正在加载课程数据...</div>
      <div v-if="!loading && errorMessage" class="bg-white rounded-lg shadow-md p-6 mb-6 text-red-600">{{ errorMessage }}</div>

      <!-- 课程列表 -->
      <div class="space-y-6">
        <div
          v-for="course in filteredCourses"
          :key="course.id"
          class="bg-white rounded-lg shadow-md p-6 hover:shadow-lg transition-shadow"
        >
          <div class="flex items-start space-x-6">
            <!-- 课程封面 -->
            <div class="flex-shrink-0">
              <div class="w-24 h-24 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg flex items-center justify-center relative overflow-hidden">
                <img
                  v-if="course.thumbnail_url"
                  :src="course.thumbnail_url"
                  :alt="course.title"
                  class="w-full h-full object-cover"
                />
                <div v-else class="text-white text-center">
                  <svg class="w-8 h-8 mx-auto mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
                  </svg>
                  <span class="text-xs font-medium">{{ course.category }}</span>
                </div>
                <!-- 视频播放图标 -->
                <div v-if="course.type === 'video'" class="absolute inset-0 flex items-center justify-center">
                  <div class="w-8 h-8 bg-black bg-opacity-50 rounded-full flex items-center justify-center">
                    <svg class="w-4 h-4 text-white ml-1" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M8 5v14l11-7z"/>
                    </svg>
                  </div>
                </div>
              </div>
            </div>

            <!-- 课程信息 -->
            <div class="flex-1">
              <div class="flex items-center justify-between mb-2">
                <h3 class="text-lg font-semibold text-gray-900">{{ course.title }}</h3>
                <span
                  :class="[
                    'px-2 py-1 rounded text-xs font-semibold',
                    course.is_completed ? 'bg-green-100 text-green-800' :
                    course.is_enrolled ? 'bg-blue-100 text-blue-800' :
                    'bg-gray-100 text-gray-800'
                  ]"
                >
                  {{ course.is_completed ? '已完成' : course.is_enrolled ? '进行中' : '未开始' }}
                </span>
              </div>
              
              <p class="text-gray-600 mb-3">{{ course.description }}</p>
              
              <div class="flex items-center space-x-4 text-sm text-gray-500 mb-3">
                <span>讲师: {{ course.instructor }}</span>
                <span>时长: {{ formatDuration(course.duration) }}</span>
                <span>难度: {{ formatDifficulty(course.difficulty) }}</span>
                <span>类型: {{ formatType(course.type) }}</span>
              </div>

              <!-- 进度条 -->
              <div class="mb-3">
                <div class="flex justify-between text-sm text-gray-600 mb-1">
                  <span>学习进度</span>
                  <span>{{ course.progress }}%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                  <div
                    class="bg-blue-600 h-2 rounded-full transition-all duration-300"
                    :style="{ width: `${course.progress}%` }"
                  ></div>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="flex items-center space-x-3">
                <button
                  class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors text-sm"
                  @click="continueCourse(course)"
                >
                  {{ course.is_completed ? '重新学习' : course.is_enrolled ? '继续学习' : '开始学习' }}
                </button>
                <button
                  class="text-gray-600 hover:text-gray-800 text-sm"
                  @click="viewCourse(course)"
                >
                  查看详情
                </button>
                <button
                  v-if="course.type === 'video'"
                  class="text-gray-600 hover:text-gray-800 text-sm"
                  @click="previewVideo(course)"
                >
                  预览视频
                </button>
                <button
                  class="text-gray-600 hover:text-gray-800 text-sm"
                  @click="toggleFavorite(course)"
                >
                  {{ course.is_favorited ? '取消收藏' : '收藏' }}
                </button>
                <button
                  class="text-gray-600 hover:text-gray-800 text-sm"
                  @click="downloadMaterials(course)"
                >
                  下载资料
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredCourses.length === 0" class="text-center py-12">
        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path>
        </svg>
        <h3 class="mt-2 text-sm font-medium text-gray-900">暂无课程</h3>
        <p class="mt-1 text-sm text-gray-500">该筛选条件下没有找到课程</p>
      </div>
    </div>

    <!-- 创建课程模态框 -->
    <div v-if="showCreateCourseModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-xl font-semibold">创建新课程</h2>
          <button @click="showCreateCourseModal = false" class="text-gray-500 hover:text-gray-700">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
          </button>
        </div>

        <form @submit.prevent="createCourse" class="space-y-4">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">课程标题 *</label>
              <input
                v-model="newCourse.title"
                type="text"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="请输入课程标题"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">讲师姓名 *</label>
              <input
                v-model="newCourse.instructor"
                type="text"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="请输入讲师姓名"
              />
            </div>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">课程描述</label>
            <textarea
              v-model="newCourse.description"
              rows="3"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入课程描述"
            ></textarea>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">课程类型 *</label>
              <select
                v-model="newCourse.type"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="video">视频课程</option>
                <option value="document">文档课程</option>
                <option value="mixed">混合课程</option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">难度等级 *</label>
              <select
                v-model="newCourse.difficulty"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
                <option value="beginner">初级</option>
                <option value="medium">中级</option>
                <option value="advanced">高级</option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">课程分类 *</label>
              <input
                v-model="newCourse.category"
                type="text"
                required
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="如：算法、编程、AI等"
              />
            </div>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">课程标签</label>
            <input
              v-model="newCourse.tags"
              type="text"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="用逗号分隔，如：数据结构,算法,编程"
            />
          </div>

          <div v-if="newCourse.type === 'video' || newCourse.type === 'mixed'">
            <label class="block text-sm font-medium text-gray-700 mb-1">视频链接 *</label>
            <input
              v-model="newCourse.video_url"
              type="url"
              required
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入B站、YouTube等视频链接"
              @blur="parseVideoUrl"
            />
            <p class="text-sm text-gray-500 mt-1">支持B站、YouTube等平台链接</p>
          </div>

          <div v-if="newCourse.type === 'video' || newCourse.type === 'mixed'">
            <label class="block text-sm font-medium text-gray-700 mb-1">视频时长（分钟）</label>
            <input
              v-model.number="newCourse.duration"
              type="number"
              min="0"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入视频时长"
            />
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">课程详细内容</label>
            <textarea
              v-model="newCourse.content"
              rows="5"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入课程的详细内容介绍"
            ></textarea>
          </div>

          <div class="flex justify-end space-x-3">
            <button
              type="button"
              @click="showCreateCourseModal = false"
              class="px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
            >
              取消
            </button>
            <button
              type="submit"
              :disabled="creatingCourse"
              class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
            >
              {{ creatingCourse ? '创建中...' : '创建课程' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 视频预览模态框 -->
    <div v-if="showVideoModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg p-6 w-full max-w-4xl max-h-[90vh] overflow-y-auto">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-xl font-semibold">{{ selectedCourse?.title }}</h2>
          <button @click="showVideoModal = false" class="text-gray-500 hover:text-gray-700">
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
            </svg>
          </button>
        </div>

        <div v-if="selectedCourse" class="space-y-4">
          <!-- 视频播放器 -->
          <div class="aspect-video bg-gray-900 rounded-lg overflow-hidden">
            <iframe
              v-if="getVideoEmbedURL(selectedCourse)"
              :src="getVideoEmbedURL(selectedCourse)"
              class="w-full h-full"
              frameborder="0"
              allowfullscreen
            ></iframe>
            <div v-else class="w-full h-full flex items-center justify-center text-white">
              <p>无法加载视频预览</p>
            </div>
          </div>

          <!-- 课程信息 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <h3 class="font-semibold text-gray-900 mb-2">课程信息</h3>
              <div class="space-y-2 text-sm">
                <p><span class="font-medium">讲师：</span>{{ selectedCourse.instructor }}</p>
                <p><span class="font-medium">时长：</span>{{ formatDuration(selectedCourse.duration) }}</p>
                <p><span class="font-medium">难度：</span>{{ formatDifficulty(selectedCourse.difficulty) }}</p>
                <p><span class="font-medium">类型：</span>{{ formatType(selectedCourse.type) }}</p>
                <p><span class="font-medium">分类：</span>{{ selectedCourse.category }}</p>
              </div>
            </div>
            <div>
              <h3 class="font-semibold text-gray-900 mb-2">课程统计</h3>
              <div class="space-y-2 text-sm">
                <p><span class="font-medium">浏览次数：</span>{{ selectedCourse.view_count }}</p>
                <p><span class="font-medium">报名人数：</span>{{ selectedCourse.enroll_count }}</p>
                <p><span class="font-medium">点赞数：</span>{{ selectedCourse.like_count }}</p>
                <p><span class="font-medium">评分：</span>{{ selectedCourse.rating.toFixed(1) }} ({{ selectedCourse.rating_count }}人评价)</p>
              </div>
            </div>
          </div>

          <!-- 课程描述 -->
          <div v-if="selectedCourse.description">
            <h3 class="font-semibold text-gray-900 mb-2">课程描述</h3>
            <p class="text-gray-600">{{ selectedCourse.description }}</p>
          </div>

          <!-- 操作按钮 -->
          <div class="flex justify-end space-x-3">
            <button
              @click="enrollCourse(selectedCourse)"
              class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
            >
              报名课程
            </button>
            <button
              @click="toggleFavorite(selectedCourse)"
              class="px-4 py-2 border border-gray-300 text-gray-600 rounded-lg hover:bg-gray-50"
            >
              {{ selectedCourse.is_favorited ? '取消收藏' : '收藏课程' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { courseApi, type Course, type CreateCourseRequest } from '@/api/course'

const route = useRoute()

// 响应式数据
const searchQuery = ref('')
const selectedStatus = ref('')
const selectedCategory = ref('')
const loading = ref(false)
const errorMessage = ref('')

// 模态框状态
const showCreateCourseModal = ref(false)
const showVideoModal = ref(false)
const selectedCourse = ref<Course | null>(null)
const creatingCourse = ref(false)

// 新课程表单数据
const newCourse = ref<CreateCourseRequest>({
  title: '',
  description: '',
  content: '',
  type: 'video',
  difficulty: 'beginner',
  category: '',
  tags: '',
  video_url: '',
  video_id: '',
  video_source: '',
  duration: 0,
  thumbnail_url: '',
  instructor: '',
  language: 'zh-CN'
})

const stats = ref({
  totalCourses: 0,
  completedCourses: 0,
  inProgressCourses: 0,
  totalHours: 0
})

// 课程数据
const courses = ref<Course[]>([])

// 计算属性
const filteredCourses = computed(() => {
  let filtered = courses.value

  // 状态过滤
  if (selectedStatus.value) {
    filtered = filtered.filter(c => c.status === selectedStatus.value)
  }

  // 分类过滤
  if (selectedCategory.value) {
    filtered = filtered.filter(c => c.category === selectedCategory.value)
  }

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(c =>
      c.title.toLowerCase().includes(query) ||
      c.description.toLowerCase().includes(query) ||
      c.instructor.toLowerCase().includes(query)
    )
  }

  return filtered
})

// 方法
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleFilter = () => {
  // 过滤逻辑已在计算属性中处理
}

const continueCourse = (course: Course) => {
  console.log('继续学习课程:', course)
  // 这里可以跳转到课程学习页面
}

const viewCourse = (course: Course) => {
  console.log('查看课程详情:', course)
  // 这里可以跳转到课程详情页面
}

const previewVideo = (course: Course) => {
  selectedCourse.value = course
  showVideoModal.value = true
}

const enrollCourse = async (course: Course) => {
  try {
    await courseApi.enrollCourse({ course_id: course.id })
    alert('报名成功！')
    // 刷新课程数据
    await loadCourses()
  } catch (error: any) {
    console.error('报名失败:', error)
    alert(error?.message || '报名失败')
  }
}

const toggleFavorite = async (course: Course) => {
  try {
    await courseApi.toggleCourseFavorite(course.id)
    // 更新本地状态
    course.is_favorited = !course.is_favorited
    course.like_count += course.is_favorited ? 1 : -1
  } catch (error: any) {
    console.error('收藏操作失败:', error)
    alert(error?.message || '操作失败')
  }
}

const downloadMaterials = async (course: Course) => {
  try {
    await courseApi.downloadCourseMaterials(course.id)
  } catch (error) {
    console.error('下载课程资料失败:', error)
  }
}

const parseVideoUrl = () => {
  if (!newCourse.value.video_url) return
  
  const videoInfo = courseApi.parseVideoUrl(newCourse.value.video_url)
  if (videoInfo) {
    newCourse.value.video_source = videoInfo.source
    newCourse.value.video_id = videoInfo.videoId
  }
}

const createCourse = async () => {
  creatingCourse.value = true
  try {
    await courseApi.createCourse(newCourse.value)
    alert('课程创建成功！')
    showCreateCourseModal.value = false
    // 重置表单
    newCourse.value = {
      title: '',
      description: '',
      content: '',
      type: 'video',
      difficulty: 'beginner',
      category: '',
      tags: '',
      video_url: '',
      video_id: '',
      video_source: '',
      duration: 0,
      thumbnail_url: '',
      instructor: '',
      language: 'zh-CN'
    }
    // 刷新课程列表
    await loadCourses()
  } catch (error: any) {
    console.error('创建课程失败:', error)
    alert(error?.message || '创建课程失败')
  } finally {
    creatingCourse.value = false
  }
}

const getVideoEmbedURL = (course: Course): string => {
  return courseApi.getVideoEmbedURL(course)
}

const formatDuration = (minutes: number): string => {
  return courseApi.formatDuration(minutes)
}

const formatDifficulty = (difficulty: string): string => {
  return courseApi.formatDifficulty(difficulty)
}

const formatType = (type: string): string => {
  return courseApi.formatType(type)
}

const loadCourses = async () => {
  const userId = Number(route.params.id)
  loading.value = true
  errorMessage.value = ''
  try {
    const [statsRes, listRes] = await Promise.all([
      courseApi.getUserCourseStats(userId),
      courseApi.getUserCourses(userId, {
        status: selectedStatus.value as any,
        category: selectedCategory.value || undefined,
        search: searchQuery.value || undefined
      })
    ])

    // 映射统计数据到前端展示结构
    const s = statsRes as any
    stats.value = {
      totalCourses: s.total_courses || 0,
      completedCourses: s.completed_courses || 0,
      inProgressCourses: s.in_progress_courses || 0,
      totalHours: s.total_hours || 0
    }

    // 设置课程列表
    const items = (listRes as any)?.items || []
    courses.value = (items || []).map((c: any) => ({
      id: c.id,
      title: c.title,
      description: c.description,
      content: c.content,
      type: c.type,
      difficulty: c.difficulty,
      category: c.category,
      tags: c.tags,
      video_url: c.video_url,
      video_id: c.video_id,
      video_source: c.video_source,
      duration: c.duration,
      thumbnail_url: c.thumbnail_url,
      instructor: c.instructor,
      instructor_id: c.instructor_id,
      language: c.language,
      status: c.status,
      view_count: c.view_count,
      enroll_count: c.enroll_count,
      like_count: c.like_count,
      rating: c.rating,
      rating_count: c.rating_count,
      progress: c.progress ?? 0,
      enrolled_at: c.enrolled_at,
      completed_at: c.completed_at,
      last_watched_at: c.last_watched_at,
      created_at: c.created_at,
      updated_at: c.updated_at,
      is_favorited: c.is_favorited || false,
      is_enrolled: c.is_enrolled || false,
      is_completed: c.is_completed || false
    }))
  } catch (error: any) {
    console.error('加载课程数据失败:', error)
    errorMessage.value = error?.message || '加载课程数据失败'
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  await loadCourses()
})
</script>
